import { ref } from "vue";

export default function useMenuSelected(menuData, currentPath) {
  const selectedKeys = ref([]);
  const openKeys = ref([]);
  const skeys = [];
  let pathname = currentPath ? currentPath : location.href.split('#')[1];

  if (pathname.split("?").length > 1) {
    pathname = pathname.split("?")[0]
  }

  findMenu(menuData, pathname, skeys)
  const obj = findParent(pathname, menuData);
  const rootSubmenuKeys = obj.rootSubmenuKeys;
  selectedKeys.value = skeys;
  openKeys.value = obj.okeys;

  return {
    openKeys,
    selectedKeys,
    rootSubmenuKeys
  }
}

function findMenu(menuData, pathname, skeys) {
  menuData.forEach(menu => {
    if (menu.children && menu.children.length > 0) {
      findMenu(menu.children, pathname, skeys)
    }

    if (menu.path === pathname) {
      skeys.push(menu.id)
    }
  })
}

function filterCheckParentPath(list, pathname, arr) {
  let okeys = [];
  list.forEach(item => {
    if (item.path === pathname) {
      okeys = arr;
    }
    if (okeys.length === 0 && item.children) {
      okeys = filterCheckParentPath(item.children, pathname, arr.concat([item.id]))
    }
  });
  return okeys;
}

function findParent(pathname, menuData) {
  let okeys = [];
  const rootSubmenuKeys = [];
  menuData.forEach(menu => {
    rootSubmenuKeys.push(menu.id);
    if (menu.children && okeys.length === 0) {
      okeys = filterCheckParentPath(menu.children, pathname, [menu.id]);
    }
  })
  return {
    okeys,
    rootSubmenuKeys
  }
}